#include "bsp_timer.h"

void bsp_timer1_init(void)
{
    /* ----------------------------------------------------------------------------
    TIMER1 Configuration: 
    TIMER1CLK = SystemCoreClock/10800 = 10KHz, the period is 1s(10000/10000 = 0.01s).
    ---------------------------------------------------------------------------- */
    timer_parameter_struct timer_initpara;

    rcu_periph_clock_enable(RCU_TIMER1);

    timer_deinit(TIMER1);
    timer_struct_para_init(&timer_initpara);
    timer_initpara.prescaler         = 10799;
    timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection  = TIMER_COUNTER_UP;
    timer_initpara.period            = 99;
    timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;
    timer_init(TIMER1, &timer_initpara);

    timer_interrupt_flag_clear(TIMER1, TIMER_INT_FLAG_UP);
    timer_interrupt_enable(TIMER1, TIMER_INT_UP);
    timer_enable(TIMER1);

    nvic_priority_group_set(NVIC_PRIGROUP_PRE1_SUB3);
    nvic_irq_enable(TIMER1_IRQn, 1, 1);
}

void bsp_timer2_init(void)
{
    timer_parameter_struct timer_initpara;
    timer_ic_parameter_struct timer_icinitpara;

    rcu_periph_clock_enable(RCU_TIMER2);
    rcu_periph_clock_enable(RCU_GPIOA);

    /**TIM2 GPIO Configuration
    PA6     ------> TIM2_CH1
    PA7     ------> TIM2_CH2 */
    //gpio_init(GPIOA, GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, GPIO_PIN_6 | GPIO_PIN_7);

    timer_deinit(TIMER2);
    timer_initpara.period = ENCODER_TIM_PERIOD;
    timer_initpara.prescaler = ENCODER_TIM_PSC;         // 预分频
    timer_initpara.alignedmode = TIMER_COUNTER_EDGE;    // 对齐方式
    timer_initpara.counterdirection = TIMER_COUNTER_UP; // 配置计数方向为向上计数
    timer_initpara.clockdivision = TIMER_CKDIV_DIV1;    // 时钟不分频
    timer_initpara.repetitioncounter = 0;               // 重载
    timer_init(TIMER2, &timer_initpara);

    /* TIMER2 CH0 input capture configuration */
    timer_icinitpara.icfilter = 0x05; // 配置滤波器
    timer_icinitpara.icpolarity = TIMER_IC_POLARITY_RISING;
    timer_icinitpara.icselection = TIMER_IC_SELECTION_DIRECTTI;
    timer_icinitpara.icprescaler = TIMER_IC_PSC_DIV1;

    timer_input_capture_config(TIMER2, TIMER_CH_0, &timer_icinitpara);
    timer_input_capture_config(TIMER2, TIMER_CH_1, &timer_icinitpara);
#if 0
    timer_quadrature_decoder_mode_config(TIMER2, \
                                         TIMER_ENCODER_MODE2, \
                                         TIMER_IC_POLARITY_BOTH_EDGE, \
                                         TIMER_IC_POLARITY_BOTH_EDGE);														
	timer_slave_mode_select(TIMER2,TIMER_ENCODER_MODE2);
#endif
    // timer_interrupt_enable(TIMER2, TIMER_INT_UP);
    // nvic_irq_enable(TIMER2_IRQn, 1, 1);//使能中断并设置优先级
    timer_auto_reload_shadow_enable(TIMER2);
    timer_enable(TIMER2);
}
